# PowerShell 配置文件优化 - 适用于程序员的配置

# 检查并安装 fzf
$fzfPath = "$env:LOCALAPPDATA\Microsoft\WindowsApps\fzf.exe"
if (-not (Test-Path $fzfPath)) {
    Write-Host "正在下载并安装 fzf..." -ForegroundColor Yellow
    $tempFile = "$env:TEMP\fzf.zip"
    $fzfVersion = "0.44.1"
    $downloadUrl = "https://github.com/junegunn/fzf/releases/download/$fzfVersion/fzf-$fzfVersion-windows_amd64.zip"
    
    try {
        Invoke-WebRequest -Uri $downloadUrl -OutFile $tempFile -UseBasicParsing
        Expand-Archive -Path $tempFile -DestinationPath "$env:LOCALAPPDATA\Microsoft\WindowsApps" -Force
        Remove-Item $tempFile -Force
        Write-Host "fzf 安装成功!" -ForegroundColor Green
    }
    catch {
        Write-Host "fzf 安装失败: $_" -ForegroundColor Red
    }
}

# 加载必要模块
$RequiredModules = @('posh-git', 'PSReadLine', 'Terminal-Icons', 'z')

# 安装和配置所有模块
foreach ($module in $RequiredModules) {
    if (!(Get-Module -ListAvailable -Name $module)) {
        Write-Host "安装 $module 模块..." -ForegroundColor Yellow
        Install-Module $module -Scope CurrentUser -Force
    }
    try {
        Import-Module $module -ErrorAction Stop
    }
    catch {
        Write-Host "无法导入模块 $($module): $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 安装和配置 PSFzf
if (Test-Path $fzfPath) {
    if (!(Get-Module -ListAvailable -Name PSFzf)) {
        Write-Host "安装 PSFzf 模块..." -ForegroundColor Yellow
        Install-Module PSFzf -Scope CurrentUser -Force
    }
    try {
        Import-Module PSFzf -ErrorAction Stop
        # 配置 PSFzf 快捷键
        Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+f' -PSReadlineChordReverseHistory 'Ctrl+r'
        Write-Host "PSFzf 配置成功! 按 Ctrl+f 搜索文件, Ctrl+r 搜索历史记录" -ForegroundColor Green
    }
    catch {
        Write-Host "无法导入模块 PSFzf: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# PowerShell 标题和窗口配置
$Host.UI.RawUI.WindowTitle = "PowerShell"
$PSDefaultParameterValues['Out-Default:OutVariable'] = $null

# PSReadLine 配置
Set-PSReadLineOption -PredictionSource History -PredictionViewStyle ListView
Set-PSReadLineOption -EditMode Windows
Set-PSReadLineOption -BellStyle None
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

# 初始化版本信息缓存
$script:versionCache = @{
    LastUpdate = $null
    Versions   = @{}
}

# 更新版本信息的函数
function Update-VersionCache {
    $currentTime = Get-Date
    if ($null -eq $script:versionCache.LastUpdate -or 
        ($currentTime - $script:versionCache.LastUpdate).TotalMinutes -ge 10) {
        
        # Python 版本
        if (Get-Command python -ErrorAction SilentlyContinue) {
            $version = (python --version 2>&1).ToString() -replace "Python ", ""
            $script:versionCache.Versions.Python = $version
        }
        
        # Node.js 版本
        if (Get-Command node -ErrorAction SilentlyContinue) {
            $version = (node --version 2>&1).ToString().Trim('v')
            $script:versionCache.Versions.Node = $version
        }
        
        # Java 版本
        if (Get-Command java -ErrorAction SilentlyContinue) {
            $version = (java -version 2>&1)[0].ToString() -replace 'java version |"'
            $script:versionCache.Versions.Java = $version
        }

        # Go 版本
        if (Get-Command go -ErrorAction SilentlyContinue) {
            $version = (go version) -replace "go version go"
            $script:versionCache.Versions.Go = ($version -split " ")[0]
        }
        
        # Rust 版本
        if (Get-Command rustc -ErrorAction SilentlyContinue) {
            $version = (rustc --version) -replace "rustc "
            $script:versionCache.Versions.Rust = ($version -split " ")[0]
        }
        
        # C# (.NET) 版本
        if (Get-Command dotnet -ErrorAction SilentlyContinue) {
            $version = (dotnet --version)
            $script:versionCache.Versions.DotNet = $version
        }
        
        $script:versionCache.LastUpdate = $currentTime
    }
}

# 提示符函数
function prompt {
    # 获取命令执行状态
    $lastCommandSuccess = $?
    $lastExitCode = $LASTEXITCODE
    
    # 更新版本缓存
    Update-VersionCache
    
    # 获取基本信息
    $location = $(Get-Location)
    $dateTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    
    # 第一行：显示路径和时间
    Write-Host "`n$location" -NoNewline
    Write-Host " [$dateTime]" -NoNewline -ForegroundColor DarkGray
    
    # Git 状态
    if (Get-Command Get-GitStatus -ErrorAction SilentlyContinue) {
        try {
            $git = Get-GitStatus
            if ($git) {
                $branch = $git.Branch
                $color = if ($git.HasWorking) { "Yellow" } elseif ($git.HasIndex) { "Green" } else { "Cyan" }
                Write-Host " [git ⎇ $branch]" -NoNewline -ForegroundColor $color
            }
        }
        catch {}
    }
    
    # 环境和版本信息
    if ($script:versionCache.Versions.Python) {
        Write-Host " [🐍 Python $($script:versionCache.Versions.Python)]" -NoNewline -ForegroundColor Blue
    }
    
    if ($env:CONDA_DEFAULT_ENV) {
        Write-Host " [Conda🐊 $env:CONDA_DEFAULT_ENV]" -NoNewline -ForegroundColor Yellow
    }
    
    if ($script:versionCache.Versions.Node) {
        Write-Host " [⬢ Nodejs $($script:versionCache.Versions.Node)]" -NoNewline -ForegroundColor Green
    }

    if ($script:versionCache.Versions.Go) {
        Write-Host " [🦫 Go $($script:versionCache.Versions.Go)]" -NoNewline -ForegroundColor Cyan
    }

    if ($script:versionCache.Versions.Rust) {
        Write-Host " [🦀 Rust $($script:versionCache.Versions.Rust)]" -NoNewline -ForegroundColor Red
    }

    if ($script:versionCache.Versions.DotNet) {
        Write-Host " [⭕.NET $($script:versionCache.Versions.DotNet)]" -NoNewline -ForegroundColor DarkMagenta
    }
    
    # 状态指示器
    try {
        $memoryUsage = [math]::Round((Get-Counter '\Memory\% Committed Bytes In Use').CounterSamples.CookedValue)
        Write-Host " [💾 Mem ${memoryUsage}%]" -NoNewline -ForegroundColor Magenta
    }
    catch {}
    
    try {
        $battery = Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue
        if ($battery) {
            $percent = $battery.EstimatedChargeRemaining
            $batteryIcon = if ($battery.BatteryStatus -eq 2) { "⚡" } else { "🔋" }
            Write-Host " [$batteryIcon $percent%]" -NoNewline -ForegroundColor $(
                if ($percent -lt 20) { "Red" } elseif ($percent -lt 50) { "Yellow" } else { "Green" }
            )
        }
    }
    catch {}
    
    # 命令执行状态
    $resultIcon = if ($lastCommandSuccess) { "✓" } else { "✗" }
    $resultColor = if ($lastCommandSuccess) { "Green" } else { "Red" }
    Write-Host " $resultIcon" -NoNewline -ForegroundColor $resultColor
    
    # 第二行：提示符
    Write-Host ""
    Write-Host "❯" -NoNewline -ForegroundColor $(if ($lastCommandSuccess) { "Green" } else { "Red" })
    
    $global:LASTEXITCODE = $lastExitCode
    return " "
}

# 增强的别名和函数
Set-Alias -Name ll -Value Get-ChildItem
Set-Alias -Name g -Value git
Set-Alias -Name py -Value python
Set-Alias -Name vim -Value nvim
Set-Alias -Name k -Value kubectl
Set-Alias -Name tf -Value terraform

# 实用的函数
function which($command) {
    Get-Command -Name $command -ErrorAction SilentlyContinue | 
    Select-Object -ExpandProperty Path
}

function touch($file) {
    if (Test-Path $file) {
        (Get-Item $file).LastWriteTime = Get-Date
    }
    else {
        New-Item -ItemType File -Path $file
    }
}

# Git 快捷命令
function gst { git status }
function ga { git add $args }
function gc { git commit -m $args }
function gp { git push }
function gl { git pull }
function gd { git diff }
function gco { git checkout $args }
function gb { git branch }
function glog {
    git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
}

# 快捷导航命令
function .. { Set-Location .. }
function ... { Set-Location ../.. }
function .... { Set-Location ../../.. }
function ~ { Set-Location $HOME }

# 显示系统信息
function Get-SystemInfo {
    $info = [ordered]@{
        "系统信息"         = (Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, OSArchitecture)
        "PowerShell版本" = $PSVersionTable.PSVersion
        "CPU使用率"       = [math]::Round((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue)
        "内存使用率"        = Get-CimInstance Win32_OperatingSystem | ForEach-Object {
            [math]::Round(($_.TotalVisibleMemorySize - $_.FreePhysicalMemory) / $_.TotalVisibleMemorySize * 100, 2)
        }
    }
    
    foreach ($key in $info.Keys) {
        Write-Host "`n$($key):" -ForegroundColor Green
        $info[$key] | Format-Table -AutoSize
    }
    
    # 显示磁盘信息
    Write-Host "`n磁盘空间:" -ForegroundColor Green
    Get-CimInstance Win32_LogicalDisk | Where-Object DriveType -eq 3 | 
    Select-Object DeviceID, @{
        Name       = "容量(GB)"
        Expression = { [math]::Round($_.Size / 1GB, 2) }
    }, @{
        Name       = "剩余(GB)"
        Expression = { [math]::Round($_.FreeSpace / 1GB, 2) }
    }, @{
        Name       = "使用率(%)"
        Expression = { [math]::Round(($_.Size - $_.FreeSpace) / $_.Size * 100, 1) }
    } | Format-Table -AutoSize
    
    # 显示进程信息
    Write-Host "`n占用 CPU 最多的进程:" -ForegroundColor Green
    Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU, WorkingSet | Format-Table -AutoSize
}

# 添加网络工具
function Get-PublicIP {
    try {
        $ip = (Invoke-WebRequest -Uri "https://api.ipify.org/" -UseBasicParsing).Content
        Write-Host "公网IP: $ip" -ForegroundColor Green
    }
    catch {
        Write-Host "无法获取公网IP" -ForegroundColor Red
    }
}

function Get-NetworkSpeed {
    $url = "http://speedtest.wdc01.softlayer.com/downloads/test10.zip"
    $output = "$env:TEMP\speedtest.zip"
    
    Write-Host "测试下载速度..." -ForegroundColor Yellow
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    
    try {
        Invoke-WebRequest -Uri $url -OutFile $output -UseBasicParsing
        $sw.Stop()
        
        $fileSize = (Get-Item $output).Length / 1MB
        $timeTaken = $sw.Elapsed.TotalSeconds
        $speedMbps = [Math]::Round(($fileSize * 8) / $timeTaken, 2)
        
        Write-Host "下载速度: $speedMbps Mbps" -ForegroundColor Green
    }
    catch {
        Write-Host "测速失败: $_" -ForegroundColor Red
    }
    finally {
        Remove-Item $output -Force -ErrorAction SilentlyContinue
    }
}

# 增强的欢迎信息
function Show-Welcome {
    $banner = @"
    
  ____                        ____  _          _ _ 
 |  _ \ _____      _____ _ __|  _ \| |__   ___| | |
 | |_) / _ \ \ /\ / / _ \ '__| |_) | '_ \ / _ \ | |
 |  __/ (_) \ V  V /  __/ |  |  __/| | | |  __/ | |
 |_|   \___/ \_/\_/ \___|_|  |_|   |_| |_|\___|_|_|
                                                   
"@
    Write-Host $banner -ForegroundColor Cyan
    Write-Host "PowerShell 7.5 已配置为增强的程序员模式!" -ForegroundColor Green
    Write-Host "提示: 输入 'Get-SystemInfo' 查看系统信息" -ForegroundColor Yellow
    Write-Host "      输入 'Get-PublicIP' 查看公网IP" -ForegroundColor Yellow
    Write-Host "      输入 'Get-NetworkSpeed' 测试网络速度" -ForegroundColor Yellow
    
    # 显示随机提示
    $tips = @(
        "使用 Tab 键自动补全命令和参数",
        "按 F7 可以查看命令历史记录",
        "使用 gst 快速查看 Git 状态",
        "按 Ctrl+R 可以搜索历史命令",
        "使用 z 命令可以快速跳转到常用目录"
    )
    $randomTip = $tips | Get-Random
    Write-Host "`n💡 提示: $randomTip" -ForegroundColor Yellow
}

# 仅在首次加载时显示欢迎信息
if (-not $env:PROFILE_LOADED) {
    Show-Welcome
    $env:PROFILE_LOADED = $true
}
